<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import type { LoginForm } from '@/api/login/type'
import { useRouter } from 'vue-router'
import type { FormRules, FormInstance } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
// 登录请求携带的参数
const loginForm: LoginForm = reactive<LoginForm>({ username: 'admin', password: '111111' })
// 定义表单校验规则
const ruleFormRef = ref<FormInstance>()
// 用户名校验规则
const validateUsername = (rule: any, value: any, callback: any) => {
  // 用户名为空
  if (!value) {
    callback(new Error('请输入用户名'))
  } else if (value.length < 5 || value.length > 20) {
    // 用户名不在5到20位之间
    callback(new Error('用户名应在5到20位之间'))
  }
  callback()
}
// 密码校验规则
const validatePassword = (rule: any, value: any, callback: any) => {
  // 用户名为空
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 5 || value.length > 20) {
    // 用户名不在5到20位之间
    callback(new Error('密码长度应该在5到20位之间'))
  }
  callback()
}
const rules = reactive<FormRules<LoginForm>>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
})
// 引入用户仓库
let userStore = useUserStore()
// 引入路由器实例
let $router = useRouter()
// 点击登录按钮，发送登录请求
const login = async () => {
  await userStore
    .login(loginForm)
    // 登录成功，跳转到首页
    .then(async (res) => {
      await $router.push({ name: 'IndexView' })
    })
    .catch((error) => {
      console.log(error)
    })
}
</script>

<template>
  <div class="login_container">
    <el-form class="login-form" ref="ruleFormRef" :model="loginForm" :rules="rules">
      <h1>Hello</h1>
      <h2>欢迎来到Mathmall</h2>
      <!--      用户名输入框-->
      <el-form-item prop="username">
        <el-input :prefix-icon="User" v-model="loginForm.username" />
      </el-form-item>
      <!--      密码输入框-->
      <el-form-item prop="password">
        <el-input type="password" :prefix-icon="Lock" show-password v-model="loginForm.password" />
      </el-form-item>
      <!--      登录按钮-->
      <el-form-item>
        <el-button type="primary" class="login-button" @click="login(ruleFormRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
  overflow: hidden;

  .login-form {
    margin-top: 30vh;
    margin-left: 50%;
    padding: 20px;
    width: 25vw;
    background: #404bc2;
    border-radius: 15px;
  }

  h1 {
    color: #fff;
    font-size: 2vw;
  }

  h2 {
    color: #fff;
    font-size: 1vw;
    margin: 20px 0;
  }

  .login-button {
    width: 100%;
  }
}
</style>
